<?php
/**
 * @file $HeadURL: tryapply.php $
 * @author $Author: LiangJian (liangjian@haibao.com) $
 * @date $Date: 2015-3-24 下午7:24:51 $
 * @brief 
 */
namespace haibao\cms\business;

use haibao\frame\data\query\Condition;
class TryApply extends \haibao\cms\business\Base{
	
	/**
	 * 获取试用产品申请记录
	 */
	public static function getApplyByQuery($query){
		if(!$query){
			$query = new \haibao\cms\model\filter\TryApply();
		}
		
		$data = new \haibao\cms\data\TryApply();
		$applyList = $data->getApplyByQuery($query);
		
		return $applyList;
	}
	
	/**
	 * 查询用户申请成功数和总数
	 */
	public static function getApplyCount($userId){
		if(!$userId){
			return false;
		}
		
		$data = new \haibao\cms\data\TryApply();
		return $data->getApplyCount($userId);
	}
	
	/**
	 * 处理审核通过
	 */
	public static function successApply($tryId, $applyIdArr){
		if(!$applyIdArr){
			throw new BusinessException('审核通过记录不能为空');
		}
		
		$tryData = new \haibao\cms\data\TryProduct();
		$tryProduct = $tryData->getTryProductById($tryId);
		
		$data = new \haibao\cms\data\TryApply();
		$successCount = $data->getSuccessCount($tryId);
		
		if($successCount >= $tryProduct->Amount){
			throw new BusinessException('超过可通过数量，不可以再审核通过！');
		}elseif($successCount + count($applyIdArr) > $tryProduct->Amount){
			$surplus = $tryProduct->Amount - $successCount;
			throw new BusinessException('勾选数量过多，还剩余'. $surplus .'项可勾选！');
		}else{
			$data->verifyApply($applyIdArr, \haibao\cms\model\data\TryApply::VERIFY_YES);
			self::pushSystemMessage($applyIdArr,false,$tryProduct);
		}
		
		self::saveOperateHistory(self::FUNC_CODE_TRYAPPLY_VERIFY_SUCCESS, $applyIdArr);
	}
	
	/**
	 * 删除申请
	 */
	public static function deleteApply($applyIdArr){
		if(!$applyIdArr){
			throw new BusinessException('删除申请记录不能为空');
		}
		$data = new \haibao\cms\data\TryApply();
		$data->dealApply($applyIdArr, \haibao\cms\model\data\TryApply::STATUS_DISABLE);
		
		self::saveOperateHistory(self::FUNC_CODE_TRYAPPLY_DELETE, $applyIdArr);
	}
	
	/**
	 * 恢复申请
	 */
	public static function recoveryApply($applyIdArr){
		if(!$applyIdArr){
			throw new BusinessException('恢复申请记录不能为空');
		}
		$data = new \haibao\cms\data\TryApply();
		$data->dealApply($applyIdArr, \haibao\cms\model\data\TryApply::STATUS_ENABLE);
		
		self::saveOperateHistory(self::FUNC_CODE_TRYAPPLY_RECOVERY, $applyIdArr);
	}
	
	/**
	 * 是否已经申请过某试用产品
	 */
	public static function isApply($userId, $tryId, $from = 'WEB'){
		$data = new \haibao\cms\data\TryApply();
		$tryApply = $data->getApplyByUserId($tryId, $userId, $from);
		return !empty($tryApply);
	}
	
	/**
	 * 是否超过可申请时间
	 */
	public static function isApplyExpire($tryId){
		$tryProduct = \haibao\cms\business\TryProduct::getTryProductById($tryId);
		return (new \DateTime()) > $tryProduct->ApplyEndTime;
	}
	
	/**
	 * 添加申请
	 * @param \haibao\cms\model\data\TryApply $model
	 * @param \haibao\cms\model\data\TryApplyUserInfo $modelUser
	 */
	public static function addTryApply($model, $modelUser){
		if(self::isApply($model->UserId, $model->TryId, \haibao\cms\model\data\TryApply::FROM_WEB)){
			throw new BusinessException('已经申请过该试用产品，不能重复申请');
		}
		if(self::isApplyExpire($model->TryId)){
			throw new BusinessException('申请时间过期，不能再申请');
		}
		self::checkForm($model, $modelUser);
		
		$model->Reason = self::filterReason($model->Reason);
		$model->IP = ip2long($model->IP);
		$model->ApplyTime = new \DateTime();
		$model->Status = \haibao\cms\model\data\TryApply::STATUS_ENABLE;
		$model->ApplyStatus = \haibao\cms\model\data\TryApply::VERIFY_NO;
		$model->From = \haibao\cms\model\data\TryApply::FROM_WEB;
		
		$data = new \haibao\cms\data\TryApply();
		$data->addTryApply($model);
		
		$userInfo = \haibao\cms\business\TryApplyUserInfo::getUserById($model->UserId);
		if($userInfo){
		    if($modelUser->TryId == $userInfo['TryId']){
		        $modelUser->Id = $userInfo['tid'];
		    }
		}
		/* 
		if($userInfo){
			$modelUser->Id = $userInfo['tid'];
		} */
		
		\haibao\cms\business\TryApplyUserInfo::saveUserInfo($modelUser);
		
		// 推送一条试用中心申请的系统消息
		self::pushSystemMessage($model);
	}
	
	/**
	 * 添加微信申请
	 * @param \haibao\cms\model\data\TryApply $model
	 */
	public static function saveWxApply($model){
	    if(!empty($_COOKIE['unionId'])){
	        $from = \haibao\cms\model\data\TryApply::FROM_WX;
	    }else{
	        $from = \haibao\cms\model\data\TryApply::FROM_WAP;
	    }
	    if(self::isApply($model->UserId, $model->TryId,$from)){
	        throw new BusinessException('已经申请过该试用产品，不能重复申请');
	    }
	    if(self::isApplyExpire($model->TryId)){
	        throw new BusinessException('申请时间过期，不能再申请');
	    }
	    if(!$model->TryId){
	        throw new BusinessException('申请的产品id不能为空');
	    }
	    if(!$model->UserId){
	        throw new BusinessException('用户id不能为空');
	    }
	    if(!$model->UserName){
	        throw new BusinessException('用户姓名不能为空');
	    }
	    if(!$model->Reason){
	        throw new BusinessException('申请理由不能为空');
	    }
	    $model->Reason = self::filterReason($model->Reason);
	    $model->ApplyTime = new \DateTime();
	    $model->IP = ip2long($model->IP);
	    $model->Status = \haibao\cms\model\data\TryApply::STATUS_ENABLE;
	    $model->ApplyStatus = \haibao\cms\model\data\TryApply::VERIFY_NO;
	    $model->From = $from;
	    
	    $data = new \haibao\cms\data\TryApply();
	    $data->addTryApply($model);
	}
	/**
	 * 添加微信申请的用户info,表为TryApplyUserInfo
	 * @param 实体 $modelUser
	 */
	public static function addTryUserInfoApply($modelUser){
	    $userInfo = \haibao\cms\business\TryApplyUserInfo::getUserById($modelUser->UserId);
	    if($userInfo){
	        if($modelUser->TryId == $userInfo['TryId']){
	            $modelUser->Id = $userInfo['tid'];
	        }
	    }
	    \haibao\cms\business\TryApplyUserInfo::saveUserInfo($modelUser);
	}
	
	/**
	 * 查询试用心得
	 */
	public static function getTryExperience($tryId,$isDetail = false,$page = null){
		if(!$tryId){
			throw new BusinessException('试用ID不能为空');
		}
		$data = new \haibao\cms\data\TryApply();
		return $data->getTryExperience($tryId,$isDetail,$page);
	}

	/**
	 * 增加PV数量
	 */
	public static function addPv($tryId){
		$data = new \haibao\cms\data\TryApply();
		$data->addPv($tryId);
	}
	
	/**
	 * 申请理由过滤非法字符
	 */
	private static function filterReason($html){
		$html = stripslashes($html);
		
		preg_match_all('/\<([^\>]+)\>/is', $html, $result);
		$searchs = array('<', '>');
		$replaces = array('&lt;', '&gt;');
		
		$html = preg_replace('/<script[^>]*>.*<\/script>/isU', '', $html);
		$html = preg_replace('/<img [^>]*>/isU', '', $html);
		
		if($result[1]){
			$allowTags = 'a|br';		//允许的标签
			$result[1] = array_unique($result[1]);
			foreach ($result[1] as $value) {
				$searchs[] = '&lt;'.$value.'&gt;';
				$value = self::shtmlSpecialchars($value);
				$value = str_replace(array('\\','/*'), array('.','/.'), $value);
				
				$value = preg_replace(array("/(javascript|script|eval|behaviour|expression)/i", "/(\s+|&quot;|')on/i"), array('.', ' .'), $value);
				if(!preg_match("/^[\/|\s]?($allowTags)(\s+|$)/is", $value)) {
					$value = '';
				}
				$replaces[] = empty($value) ? '' : "<".str_replace('&quot;', '"', $value).">";
			}
		}
		$html = str_replace($searchs, $replaces, $html);
		return addslashes($html);
	}
	
	/**
	 * 特殊字符处理
	 */
	private static function shtmlSpecialchars($string){
		if(is_array($string)) {
			foreach($string as $key => $val) {
				$string[$key] = shtmlspecialchars($val);
			}
		} else {
			$string = preg_replace('/&amp;((#(\d{3,5}|x[a-fA-F0-9]{4})|[a-zA-Z][a-z0-9]{2,5});)/', '&\\1', str_replace(array('&', '"', '<', '>'), array('&amp;', '&quot;', '&lt;', '&gt;'), $string));
		}
		return $string;
	}
	
	/**
	 * 验证表单
	 * @param \haibao\cms\model\data\TryApply $model
	 * @param \haibao\cms\model\data\TryApplyUserInfo $modelUser
	 */
	private static function checkForm($model, $modelUser){
		if(!$model->TryId){
			throw new BusinessException('申请的产品id不能为空');
		}
		if(!$model->UserId){
			throw new BusinessException('用户id不能为空');
		}
		if(!$model->Reason){
			throw new BusinessException('申请理由不能为空');
		}
		if(!$modelUser->RealName){
			throw new BusinessException('收货人姓名不能为空');
		}
		/* if(!$modelUser->Email){
			throw new BusinessException('收货人邮箱不能为空');
		} */
		if(!$modelUser->Phone){
			throw new BusinessException('收货人手机号码不能为空');
		}
		if(!$modelUser->Province || !$modelUser->City || !$modelUser->Address){
			throw new BusinessException('收货人详细地址不完全');
		}
	}
	
	/**
	 * 回复日志
	 */
	public static function replyLog($logArray){		
		$data = new \haibao\cms\data\TryApply();
		$data->replyLog($logArray);
	}
	
	/**
	 * 得到用户id
	 * @param unknown $contentArr
	 */
	public static function commonMember($contentArr){
		$data = new \haibao\cms\data\TryApply();
		return $data->commonMember($contentArr);
	}
	/**
	 * 批量刷回复
	 */
	public static function batchAddTryApply($tryApplyInfos){
		if(!$tryApplyInfos){
			return false;
		}
		$data = new \haibao\cms\data\TryApply();
		$data->addAll($tryApplyInfos);
		return true;
	}
	
	/**
	 * 
	 */
	public static function editViewNum($model){
		if(!$model->PV){
			return false;
		}
		if(!$model->TryId){
			return false;
		}		
		$data = new \haibao\cms\data\TryApply();
		$data->editViewNum($model);
		return true;
	}
	
/**
	 * 推送一条试用中心申请的系统消息
	 */
	private static function pushSystemMessage($tryApply,$isApply = true,$tryProduct = null){
		
		if($isApply){
			$data = new \haibao\cms\data\TryProduct();
			$tryProductInfo = $data->getTryProductById($tryApply->TryId);
			if($tryProductInfo){
				$messageContent = '您已成功提交申请<a href="'.\haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\Config::CLASSLIBRARY_CONFIG_HOST_TRY).'/try/'.$tryApply->TryId.'/" target="_blank">&nbsp;'.$tryProductInfo->Title.'&nbsp;</a>，若被选中将第一时间收到消息盒子通知推送。您也可以在个人中心-<a href="'.\haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\Config::CLASSLIBRARY_CONFIG_HOST_BBS).'/home.php?mod=space&do=order&tab=tryout" target="_blank">我的订单</a>中查看申请记录。';
				$userInfo['_auth_user_id'] = $tryApply->UserId;
				\haibao\www\business\message\MessageUser::addMessageInfoForSystem($userInfo,$messageContent,false);
				\haibao\www\business\message\MessageUser::updateMessageUser($tryApply->UserId,\haibao\www\model\data\message\MessageBox::MESSAGE_TYPE_SYSTEM);
				
				// DO : 推送动态
				$msgContent['MsgContent'] = array(
						'InfoId'=>(int)$tryApply->TryId,
						'InfoType'=>\haibao\user\model\data\UserDynamics::INFO_TYPE_APPLY_TRY,
						'MsgType'=>\haibao\user\model\data\UserDynamics::MESSAGE_TYPE_APPLY_TRY,
						'Title'=>$tryProductInfo->Title,
						'InfoUrl'=>\haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\Config::CLASSLIBRARY_CONFIG_HOST_TRY).'/try/'.$tryApply->TryId.'/'
				);
				$msgContent['UserId'] = $tryApply->UserId;
				\haibao\user\business\UserDynamics::addUserDynamics($msgContent);
			
			}
		}else{
			$filter = new \haibao\cms\model\filter\TryApply();
			$filter->select(array(
					\haibao\cms\model\filter\TryApply::CONDITION_FIELD_NAME_USER_ID
			));
			$filter->where(\haibao\cms\model\filter\TryApply::CONDITION_FIELD_NAME_ID,Condition::CONDITION_IN,$tryApply);
			$data = new \haibao\cms\data\TryApply();
			$tryApplyList = $data->getAll($filter);
			
			$messageContent = '恭喜贺喜！您成功获得<a href="'.\haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\Config::CLASSLIBRARY_CONFIG_HOST_TRY).'/try/'.$tryProduct->Id.'/" target="_blank">&nbsp;'.$tryProduct->Title.'&nbsp;</a>免费试用资格！等待海报君联系你收货吧，记得要按时回来献上心得哦。';
			foreach($tryApplyList as $tryApply){
				$userInfo['_auth_user_id'] = $tryApply->UserId;
				\haibao\www\business\message\MessageUser::addMessageInfoForSystem($userInfo,$messageContent,false);
				//\haibao\www\business\message\MessageUser::updateMessageUser($tryApply->UserId,\haibao\www\model\data\message\MessageBox::MESSAGE_TYPE_SYSTEM);
			}
		}
	}
	
	public static function hasTryOut($uid, $tryIdArr){
	    $data = new \haibao\cms\data\TryApply();
	    return $data->getApplyArrByUserId($uid, $tryIdArr);
	}
}